package com.zhangguo.bookstore.controller;

import com.github.pagehelper.PageInfo;
import com.zhangguo.bookstore.entity.Book;
import com.zhangguo.bookstore.service.BookService;
import com.zhangguo.bookstore.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;

/**图书控制器*/
@RestController
@RequestMapping("/api")
public class BookController {
    @Autowired
    BookService bookService;

    @GetMapping("/books")
    public PageInfo<Book> findBooks(@RequestParam(required = false,defaultValue ="") String title,
                                    @RequestParam(required = false,defaultValue ="")String author,
                                    @RequestParam(required = false,defaultValue ="")String isbn,
                                    @RequestParam(required = false) Date publishDate,
                                    @RequestParam(required = false,defaultValue ="1")int pageNum,
                                    @RequestParam(required = false,defaultValue ="10")int pageSize){
        Book book=new Book(0,title,author,0,publishDate,isbn,null);
        return bookService.selectBooks(book,pageNum,pageSize);
    }

    @DeleteMapping("/books/{id}")
    public R deleteBook(@PathVariable int id){
        int result=bookService.deleteBook(id);
        if(result>0){
           return R.ok();
        }
        return R.error();
    }

    @PostMapping("/books")
    public R addBook(@RequestBody Book book){
        int result=bookService.addBook(book);
        if(result>0){
            return R.ok();
        }
        return R.error();
    }

    @Value("${prop.up-folder}")
    String up_folder;

    @PostMapping("/upfile")
    public R upfile(@RequestPart MultipartFile file,@RequestParam String name) throws IOException {
        String oldname=file.getOriginalFilename();
        String path=up_folder+name+oldname.substring(oldname.lastIndexOf("."));
        file.transferTo(new File(path));
        return R.ok();
    }

    @GetMapping("/book/{id}")
    public R selectBook(@PathVariable int id)
    {
        Book book=bookService.selectBook(id);
        return  R.ok(book);
    }

    @PutMapping("/books")
    public R editBook(@RequestBody Book book){
        int result=bookService.editBook(book);
        if(result>0){
            return R.ok();
        }
        return R.error();
    }
}
